using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace Extensions.Configuration.Database
{
    /// <summary>
    /// Represents database as an <see cref="IConfigurationSource"/>.
    /// (数据库配置源实现)
    /// </summary>
    public class DatabaseConfigurationSource : IConfigurationSource
    {
        /// <summary>
        /// Used to access the contents of the database.
        /// </summary>
        public IDatabaseProvider DatabaseProvider { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public Action<DbContextOptionsBuilder> DatabaseOptions { get; set; }

        /// <summary>
        /// Determines whether the source will be loaded if the underlying file changes.
        /// </summary>
        public bool ReloadOnChange { get; set; }

        /// <summary>
        /// Will be called if an uncaught exception occurs in DatabaseConfigurationProvider.Load.
        /// </summary>
        public Action<DatabaseLoadExceptionContext> OnLoadException { get; set; }

        public IConfigurationProvider Build(IConfigurationBuilder builder)
        {
            this.DatabaseProvider ??= builder.GetDefaultDatabaseProvider();
            this.OnLoadException ??= builder.GetDatabaseLoadExceptionHandler();

            return new DatabaseConfigurationProvider(this);
        }
    }
}